import json
from urllib.parse import urlencode
from urllib.request import urlopen
from django.conf import settings
from urllib.parse import parse_qs
import logging



from oauth import constants
from oauth.exception import AboutQQexception
from itsdangerous import TimedJSONWebSignatureSerializer as TJWSSerializer
logger=logging.getLogger('django')
class OAuthQQ(object):
    '''def __init__(self, app_id=None, app_key=None, redirect_uri=None, state=None):
        self.app_id = app_id or settings.QQ_APP_ID
        self.app_key = app_key or settings.QQ_APP_KEY
        self.redirect_url = redirect_uri or settings.QQ_REDIRECT_URL
        self.state = state or '/'  # 用于保存登录成功后的跳转页面路径'''
    def __init__(self,app_id=None,app_key=None,redirect_uri=None,state=None):
        self.app_id=app_id or settings.QQ_APP_ID
        self.app_key = app_key or settings.QQ_APP_KEY
        self.redirect_uri=redirect_uri or settings.QQ_REDIRECT_URI
        self.state=state or '/'

    def get_auth_url(self):
        url = 'https://graph.qq.com/oauth2.0/authorize?'
        data={
            'response_type': 'code',
            'client_id': self.app_id,
            'redirect_uri': self.redirect_uri,
            'state': self.state,
            'scope': 'get_user_info',
        }
        s=urlencode(data)
        url+=s
        return url

    def get_access_token(self,code):
        url = 'https://graph.qq.com/oauth2.0/token?'
        data={
            'grant_type':'authorization_code',
            'client_id':self.app_id,
            'client_secret':self.app_key,
            'code':code,
            'redirect_uri':self.redirect_uri
        }
        s=urlencode(data)
        url+=s
        response=None
        try:
            response=urlopen(url)
            response=response.read().decode()
        except AboutQQexception as e:
            logger.error(e)
        ret_dict=parse_qs(response)
        access_token=ret_dict['access_token'][0]
        return access_token

    def get_openid(self,access_token):
        url='https://graph.qq.com/oauth2.0/me?access_token='+access_token
        response=urlopen(url)
        response=response.read().decode()
        # callback( {"client_id":"YOUR_APPID","openid":"YOUR_OPENID"} );
        '''
         url = 'https://graph.qq.com/oauth2.0/me?access_token=' + access_token
        response = urlopen(url)
        response_data = response.read().decode()
        try:
            # 返回的数据 callback( {"client_id":"YOUR_APPID","openid":"YOUR_OPENID"} )\n;
            data = json.loads(response_data[10:-4])
        except Exception:
            data = parse_qs(response_data)
            logger.error('code=%s msg=%s' % (data.get('code'), data.get('msg')))
            raise QQAPIError
        openid = data.get('openid', None)
        return openid
        '''
        data=json.loads(response[10:-4])
        openid = data.get('openid', None)
        print(openid)
        return openid
    @staticmethod
    def generate_save_user_token(openid):
        serializer = TJWSSerializer(settings.SECRET_KEY, expires_in=constants.SET_PASSWORD_TOKEN_EXPIRES)
        data = {'openid': openid}
        token = serializer.dumps(data)
        return token.decode()



        # else:
        #     if user_id != str(data.get('user_id')):
        #         return False
        #     else:
        #         return True



